from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
import redis
import json

app = Flask(__name__)
# 配置数据库连接 URI，需根据实际情况修改以下信息
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123123@127.0.0.1:3306/z1'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

# 定义一个全局变量来标记是否已经创建了表
tables_created = False

# 配置 Redis 连接
redis_client = redis.Redis(host='127.0.0.1', port=6379, db=0)


# 定义数据模型
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), nullable=False)
    age = db.Column(db.Integer, nullable=False)


# 在第一次请求时创建数据库表
@app.before_request
def create_tables():
    global tables_created
    if not tables_created:
        db.create_all()
        tables_created = True


# 添加用户数据的路由
@app.route('/add', methods=['POST'])
def add_user():
    data = request.get_json()
    name = data.get('name')
    age = data.get('age')
    if not name or not age:
        return jsonify({"error": "Name and age are required"}), 400
    new_user = User(name=name, age=age)
    try:
        db.session.add(new_user)
        db.session.commit()
        # 当添加新用户时，清除 Redis 中的用户缓存
        redis_client.delete('users')
        return jsonify({"message": "User added successfully"}), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({"error": str(e)}), 500


# 查询所有用户数据的路由
@app.route('/get', methods=['GET'])
def get_users():
    # 先尝试从 Redis 缓存中获取用户数据
    cached_users = redis_client.get('users')
    if cached_users:
        users = json.loads(cached_users)
        return jsonify(users), 200
    try:
        users = User.query.all()
        user_list = [{"id": user.id, "name": user.name, "age": user.age} for user in users]
        # 将查询到的用户数据存入 Redis 缓存
        redis_client.set('users', json.dumps(user_list))
        return jsonify(user_list), 200
    except Exception as e:
        return jsonify({"error": str(e)}), 500


if __name__ == '__main__':
    app.run(debug=True, port=8899)
